﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;

namespace Tweets.Library
{
    // http://cgeers.com/2011/09/25/writing-a-custom-json-net-datetime-converter/
    /// <summary>
    /// Date/time converter for Twitter date/time.
    /// </summary>
    public class TwitterDateTimeConverter : DateTimeConverterBase
    {
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The JsonReader to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.String)
            {
                throw new Exception(
                    String.Format("Unexpected token parsing date. Expected string, got {0}.",
                    reader.TokenType));
            }

            string dt = (string)reader.Value;
            DateTime date = TwitterBase.ParseTwitterDate(dt);

            return date;
        }

        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The JsonWriter to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            string dt;
            if (value is DateTime)
            {
                dt = ((DateTime)value).ToString(TwitterBase.TwitterDateTimeFormat);
            }
            else
            {
                throw new Exception("Expected date object value.");
            }
            writer.WriteValue(dt);
        }
    }
}
